/**
 * 
 */
package userController;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;

import mail.MailSender;

import org.apache.commons.lang3.StringUtils;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import userEntity.LoginEntity;
import userEntity.UserEntity;
import userLogic.CreateUserLogic;
import userLogic.LoginLogic;
import userLogic.UserLogic;
import validator.Validator;

/**
 * @author Yokesh Kumar
 *
 */
public class UserController implements Initializable{

	@FXML
	private TextField name;
	@FXML
	private TextField phoneNumber,UphoneNumber;
	@FXML
	private TextField emailAddress;
	@FXML
	private TextField address;
	@FXML
	private TextField postalcode;
	@FXML
	private PasswordField oldPwd;
	@FXML
	private PasswordField newPwd;
	@FXML
	private PasswordField confirmPwd;
	@FXML
	private ChoiceBox<String> vehicleClass;
	@FXML
	private ChoiceBox<String> vehicleStatus;
	@FXML
	private TextField employeeID;
	@FXML
	private TextField loginId,UloginId;
	@FXML
	private Label searchUser,ULoginInvalid,ULoginInvalid1,UPhoneInvalid1,UPhoneInvalid,newPwdInvalid,confirmPwdInvalid,message;
	@FXML
	private Pane UpdatePwdPane;

	@FXML
	private TextField phNumber_edit_profile_fxid;

	@FXML
	private TextField name_edit_profile_fxid;

	@FXML
	private TextField email_edit_profile_fxid;

	@FXML
	private TextField address_edit_profile_fxid;

	@FXML
	private TextField pincode_edit_profile_fxid;

	@FXML
	private PasswordField currentPassword_fxid;

	@FXML
	private PasswordField newPassword_fxid;

	@FXML
	private PasswordField retypePassword_fxid;

	@FXML
	private  Label msg_fxid,EditMessage;

	private static UserEntity userEntity;

   /**
    * This method is executed when manager or clerk clicks search user
    * button while editing customer's profile
    * Precondition: enter customer's Phone Number
    * Postcondition: displays customer's details
    * @param event
    */
	@FXML
	private TextField PhoneNoCustomer;
	@FXML
	private  Label searchLabelC;

	private static String emailId;

	@FXML
	public void searchCustomer(ActionEvent event)
	{
		CreateUserLogic create = new CreateUserLogic();
	   if(PhoneNoCustomer.getText().isEmpty())
	   {
		   searchLabelC.setText("Please enter Phone Number");
	   }
	   else
	   {
		   if(Validator.validatePhoneNumber(PhoneNoCustomer.getText().trim()))
		   {
			   if(!create.checkPhoneNumber("+1".concat(PhoneNoCustomer.getText().trim())))
			   {
				   this.editProfile("+1".concat(PhoneNoCustomer.getText().trim()));
			   }
			   else
				   searchLabelC.setText("Phone number does not exist");
		   }
		   else
			   searchLabelC.setText("Invalid entry");
	   }
   }
   static String Phone = "";
   
   
	/**
	 * This method is executed when editProfile is invoked
	 * Precondition: user is logged in and clicks editProfile
	 * Postcondition: displays user's details that can be changed
	 * @throws SQLException
	 */
	public void editProfile(String PhoneNumber){
		try
		{
			Phone = PhoneNumber;
			UserLogic uselog = new UserLogic();
			userEntity = new UserEntity();
			userEntity = uselog.fetchUserDetails(PhoneNumber);
			System.out.println(userEntity.getName());
			Navigator.setInitailize(true);
			Navigator.loadStackPane(Navigator.EDITPROFILEFXML);
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			EditMessage.setText("Connection Failed..Try Again!");
		}
	}

	/**
	 * This method updates the profile of the user
	 * Precondition: editProfile method displayed user details
	 * Postcondition: Profile is updated
	 * @param event
	 * @throws SQLException
	 */
	@FXML
	public void changeProfile(ActionEvent event){
		EditMessage.setText("");
		System.out.println("Saving the updated value");
		UserLogic uselogupdate = new UserLogic();
		int update = 0;
		if(phNumber_edit_profile_fxid.getText().isEmpty() || name_edit_profile_fxid.getText().isEmpty())
		{
			EditMessage.setText("Required Fields missing");
		}
		else
		{
			if(Validator.validatePhoneNumber(phNumber_edit_profile_fxid.getText().trim())){
				if(Phone.equals("+1".concat(phNumber_edit_profile_fxid.getText().trim())))
				{
					update=1;
				}
				else
				{
					CreateUserLogic create = new CreateUserLogic();
					if(!create.checkPhoneNumber("+1".concat(phNumber_edit_profile_fxid.getText())))
					{
						EditMessage.setText("Phone Number already exists");
					}
					else
						update=1;
				}
			}
			else
				EditMessage.setText("Invalid Phone Number");

		}
	   if(!Validator.validateEmailID(email_edit_profile_fxid.getText().trim()))
	    {
	    	update=0;
	    	EditMessage.setText("Invalid EmailId");
	    }
	   if(update==1)
		{
			System.out.println("Updating");
			try{

			userEntity=null;
			UserEntity userEntity = new UserEntity();
			userEntity.setOldPhoneNumber(Phone);
		userEntity.setPhoneNumber("+1".concat(phNumber_edit_profile_fxid.getText()));
		userEntity.setName(name_edit_profile_fxid.getText());
		userEntity.setEmailID(email_edit_profile_fxid.getText());
		userEntity.setAddress(address_edit_profile_fxid.getText());
		userEntity.setPincode(pincode_edit_profile_fxid.getText());
		uselogupdate.updateUserDetails(userEntity);
		Navigator.setPhoneNumber(userEntity.getPhoneNumber());
		System.out.println("Old phone number is "+Phone);
		Phone = userEntity.getPhoneNumber();
		EditMessage.setText("Profile Updated Successfully"); 
		}
		 catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				EditMessage.setText("Connection Failed..Try Again!");
			}	
		}
	}

	static int page=0;
	/**
	 * This method is invoked when user clicks change password
	 * Precondition: user is logged in
	 * Postcondition: change password form is loaded
	 */
	public void changePassword(){
		// load change password frame

		System.out.println("Loading Change Password Form");
		page=1;
		Navigator.loadStackPane(Navigator.CHANGEPASSWORDFXML);
	}

	/**
	 * This method is executed when user clicks submit button
	 * while changing password
	 * Precondition: all fields must be filled in change password form
	 * Postcondition: Password updated successfully
	 * @param event
	 */
	@FXML
	public void confirmChangePwd(ActionEvent event){
		try
		{
			Navigator.setInitailize(false);
			System.out.println("ConfirmChangePwd Method invoked");
			UserLogic uselog = new UserLogic();
			userEntity = new UserEntity();	
			if(currentPassword_fxid.getText().isEmpty() || newPassword_fxid.getText().isEmpty() || retypePassword_fxid.getText().isEmpty())
			{
				msg_fxid.setText("Missing required fields");
			}
			else
			{
				if(!Validator.verifyPwd(newPassword_fxid.getText().trim(), retypePassword_fxid.getText().trim()))
				{
					msg_fxid.setText("New Password and Retype new password fields do not match");
				}
				else
				{
					if(uselog.verifyOldPassword(Navigator.getPhoneNumber(),currentPassword_fxid.getText()))
					{
						uselog.changePwd(Navigator.getPhoneNumber(), newPassword_fxid.getText().trim());
						msg_fxid.setText("Password updated successfully");
						msg_fxid.setTextFill(Color.GREEN);
					}
					else
					{
						msg_fxid.setText("Current password is incorrect");
					}
				}
			}}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg_fxid.setText("Connection Failed..Try Again!");
		} catch (Exception e) {
			msg_fxid.setText("Connection Failed..Try Again!");
			e.printStackTrace();
		}}

	/**
	 * This method is invoked when system admin clicks search user button
	 * while resetting the password
	 * Precondition: system admin is resetting the password
	 * Postcondition: displays user details
	 * 
	 * @param event
	 */

	@FXML
	public void searchUserForChangePassword(ActionEvent event){
		try
		{
			UserLogic logic = new UserLogic();
			UserEntity user = new UserEntity();
			LoginLogic login = new LoginLogic();
			LoginEntity lentity = new LoginEntity();
			CreateUserLogic create = new CreateUserLogic();
			UpdatePwdPane.setDisable(true);
			name.setText("");
			UphoneNumber.setText("");
			UloginId.setText("");
			newPwd.setText("");
			confirmPwd.setText("");
			message.setText("");

			if(loginId.getText().isEmpty() && phoneNumber.getText().isEmpty())
			{
				searchUser.setText("Enter either phone number or Login ID");
			}
			else
			{
				if(!phoneNumber.getText().isEmpty())
				{
					if(Validator.validatePhoneNumber(phoneNumber.getText().trim()))
					{
						if(!create.checkPhoneNumber("+1".concat(phoneNumber.getText().trim())))
						{
							if(create.checkUserStatus("+1".concat(phoneNumber.getText().trim())))
							{

								user = logic.fetchUserDetails("+1".concat(phoneNumber.getText().trim()));
								if(user.getEmailID() != null && !StringUtils.isEmpty(user.getEmailID())){
									emailId = user.getEmailID();
								}
								name.setText(user.getName());
								UphoneNumber.setText(phoneNumber.getText().trim());
								UloginId.setText(login.fetchLoginId("+1".concat(phoneNumber.getText().trim())));
								UpdatePwdPane.setDisable(false);
								UPhoneInvalid.setVisible(false);
								ULoginInvalid.setVisible(false);
								searchUser.setText("");
							}
							else
							{
								searchUser.setText("User is not active");
								UPhoneInvalid.setVisible(false);
								ULoginInvalid.setVisible(false);
							}
						}
						else
						{
							UPhoneInvalid.setVisible(true);
							UPhoneInvalid.setText("Phone number does not exist");
							ULoginInvalid.setVisible(false);
							searchUser.setText("");
						}
					}
					else
					{
						UPhoneInvalid.setVisible(true);
						UPhoneInvalid.setText("Phone number is Invalid");
						ULoginInvalid.setVisible(false);
						searchUser.setText("");

					}
				}

				else
				{
					if(!create.checkLoginId(loginId.getText().trim()))
					{
						if(create.checkStatus(loginId.getText().trim()))
						{
							UloginId.setText(loginId.getText().trim());
							lentity.setLoginId(loginId.getText().trim());
							String Phone=login.fetchPhoneNumber(lentity);
							Phone = Phone.substring(2);
							UphoneNumber.setText(Phone);
							user = logic.fetchUserDetails("+1".concat(UphoneNumber.getText().trim()));
							if(user.getEmailID() != null && !StringUtils.isEmpty(user.getEmailID())){
								emailId = user.getEmailID();
							}
							name.setText(user.getName());
							UpdatePwdPane.setDisable(false);
							UPhoneInvalid.setVisible(false);
							ULoginInvalid.setVisible(false);
							searchUser.setText("");
						}
						else
						{
							searchUser.setText("User is not active");
							UPhoneInvalid.setVisible(false);
							ULoginInvalid.setVisible(false);
						}
					}
					else
					{
						ULoginInvalid.setVisible(true);
						ULoginInvalid.setText("LoginID does not exist");
						UPhoneInvalid.setVisible(false);
						searchUser.setText("");
					}
				}
			}	}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			searchUser.setText("Connection Failed..Try Again!");
		}
	}

	/**
	 * This method executes when system admin clicks update password button
	 * Precondition: searchUserForChangePassword method diplayed user details
	 * Postcondition: Password is updated
	 * @param event
	 */
	@FXML
	public void updatePwd(ActionEvent event){
		try
		{
		UserLogic ulogic = new UserLogic();
		if(newPwd.getText().isEmpty() || confirmPwd.getText().isEmpty())
		{
			newPwdInvalid.setVisible(true);
			confirmPwdInvalid.setVisible(true);
		}
		else
		{
     		if(Validator.verifyPwd(newPwd.getText().trim(), confirmPwd.getText().trim()))
				{
					newPwdInvalid.setVisible(false);
					confirmPwdInvalid.setVisible(false);

					ulogic.changePwd("+1".concat(UphoneNumber.getText().trim()), newPwd.getText().trim());
					if(emailId != null && !StringUtils.isEmpty(emailId)){
						String text = "Dear SuperRent User, Your Password is reset by Admin. Your new Password + " + newPwd.getText().trim();
						String subject = "Your SuperRent Login password is reset";
						MailSender.send(text, subject, emailId);
					}
					emailId= "";
					message.setText("Password is updated");
					message.setTextFill(Color.GREEN);
				}
				else
				{
					newPwdInvalid.setVisible(true);
					confirmPwdInvalid.setVisible(true);
					message.setText("New Password and Confirm Password does not match");
				}
			}}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message.setText("Connection failed..Try Again!");
		} catch (Exception e) {
			message.setText("Connection failed..Try Again!");
			e.printStackTrace();
		}

	}


	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		System.out.println(userEntity);
		if(Navigator.isInitailize() && userEntity != null){
			Validator.addTextLimiter(phNumber_edit_profile_fxid, 10);
			Validator.addTextLimiter(name_edit_profile_fxid, 30);
			Validator.addTextLimiter(email_edit_profile_fxid, 40);
			Validator.addTextLimiter(address_edit_profile_fxid, 30);
			Validator.addTextLimiter(pincode_edit_profile_fxid, 6);
			String Phone = userEntity.getPhoneNumber();
			Phone = Phone.substring(2);
			phNumber_edit_profile_fxid.setText(Phone);
			name_edit_profile_fxid.setText(userEntity.getName());
			email_edit_profile_fxid.setText(userEntity.getEmailID());
			address_edit_profile_fxid.setText(userEntity.getAddress());
			pincode_edit_profile_fxid.setText(userEntity.getPincode());
			userEntity = null;
			Navigator.setInitailize(false);
		}
		else if(Navigator.isInitailize()){
			Validator.addTextLimiter(loginId, 10);
			Validator.addTextLimiter(phoneNumber, 10);
			Validator.addTextLimiter(newPwd, 15);
			Validator.addTextLimiter(confirmPwd, 15);
			Navigator.setInitailize(false);
		}
		if(page==1)
		{
			Validator.addTextLimiter(currentPassword_fxid, 15);
			Validator.addTextLimiter(newPassword_fxid, 15);
			Validator.addTextLimiter(retypePassword_fxid, 15);
			page = 0;
		}
		if(page == 5){
			Validator.addTextLimiter(PhoneNoCustomer, 10);
			page = 0;
		}
	}


}
